/*
 * This class is the ticket machine of the bank. It provides tickets for customers.
 * To prevent generating conflict tickets, it must be a singleton class.
 * Copy right with Charles. You are free to use and modify the code. Please contact author - charles@webcheng.net for commercial use.
 * */


package net.webcheng;

import java.util.ArrayList;

public class TicketMachine {
	private static int sequence;
	private static ArrayList<Ticket> commonTickets = new ArrayList<Ticket>();//common customer waiting queue
	private static ArrayList<Ticket> vipTickets = new ArrayList<Ticket>();//vip customer waiting queue
	private static ArrayList<Ticket> expressTickets = new ArrayList<Ticket>();//express customer waiting queue
	
	//Use a private static class to load this TicketMachine class.
	private static final class A{
		public static final TicketMachine t = new TicketMachine();
	}
	
	private TicketMachine(){
		System.out.println("creating the ticket machine class");
	}
	
	//When customer come in, generate a ticket for the customer. Must be synchronized to avoid thread conflicts.
	public synchronized Ticket generateTicket(TicketType type){
		Ticket t = new Ticket();
		t.setSequenceNo(sequence++);
		t.setTicketType(type);
		switch(type){
		case COMMON:
			commonTickets.add(t);
			break;
		case EXPRESS:
			expressTickets.add(t);
			break;
		case VIP:
			vipTickets.add(t);
			break;
		}
		return t;
	}
	
	//When customer is called, return the first available ticket and delete it from the waiting queue.
	public synchronized Ticket fetchTicketWithType(TicketType type){
		switch(type){
		case COMMON:
			if(commonTickets.size()>0)
				return commonTickets.remove(0);
			break;
		case EXPRESS:
			if(expressTickets.size()>0)
				return expressTickets.remove(0);
			break;
		case VIP:
			if(vipTickets.size()>0)
				return vipTickets.remove(0);
			break;
		}
		return null;
	}
	
	//load the current singleton class
	public static TicketMachine getInstance(){
		return A.t;
	}
}
